<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="node_modules/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app" style="width:500px; margin: 0 auto;">
    <textarea style="width: 500px;height: 300px;" v-model="content"></textarea>
    <button @click="run">运行组件</button>
  </div>
  <div id="run-result"></div>
  <script>
    new Vue({
      el:"#app",
      data: {
        content: "" 
      },
      created() {
        this.content = `
        <template>
          <div class="hh">{{a}}</div>
        </template>
        \<script\>
        export default {
          data() {
            return{
              a:'hh,我是弹框组件'
            }
          }
        }
        \</script\>
        <style scoped>
        .hh{
          color:red;
        }
        </style>
        `
      },
      methods: {
        getSource(type) {
          const reg = new RegExp(`<${type}[^>]*>`);
          let content= this.content;
          let matches= content.match(reg);
          if(matches) {
            let start = content.indexOf(matches[0]) + matches[0].length;

            let end = content.lastIndexOf(`</${type}`);
            return content.slice(start, end);
          }
        },
        run() {
          //Vue.extend 内部会继承Vue的构造函数， 我们可以自己进行实例化操作，并且手动挂载到指定的位置

          // 获取到不同的脚本 script, template, css 
          let template = this.getSource('template');
          
          let script = this.getSource('script').replace(/export default/, 'return');
          
          let styleCss = this.getSource('style');
          
          let obj = new Function(script)();

          // console.log(template, obj, styleCss);
          //弹框组件
          obj.template = template;
          let ChildComponent = Vue.extend(obj);
          let styleEle = document.createElement('style');
          styleEle.innerHTML = styleCss;
          document.body.appendChild(styleEle); 

          new ChildComponent().$mount('#run-result');
          // Vue ast语法树来解析


          // let content = this.content;
          // let childComponent = Vue.extend({
          //   template: '<div>hello word {{msg}}</div>',
          //   data() {
          //     return {
          //       msg: 'milly'
          //     }
          //   }
          // });
          // new childComponent().$mount('#run-result')
        }
      }
    })
  </script>
</body>
</html>